#include "HttpRequest.h"

#include <boost/algorithm/string.hpp>
#include <boost/beast/http/string_body.hpp>
#include <string/stringsplit.h>

using namespace std;
namespace rdhttp {

    void HttpRequest::parser_parts() {
        string boundary = content_type().boundary();
        std::string_view content(body());
        // string_view content((char *)buf.data, buf.size);

        auto start_boundary = "--" + boundary + "\r\n";
        if (boost::starts_with(content, start_boundary)) content.remove_prefix(start_boundary.size());

        auto end_boundary = "--" + boundary + "--\r\n";
        if (boost::ends_with(content, end_boundary)) content.remove_suffix(end_boundary.size());

        auto list = rdhttp::split(content, "--" + boundary + "\r\n");

        for (auto&& i : list) {
            // cout << "++++" << i << "____" << endl;
            m_forms.emplace_back(i);
        }
    }

    HttpRequest::HttpRequest(boost::beast::http::request<boost::beast::http::string_body>&& _req) {
        auto* p_head = static_cast<HttpRequest::header_type*>(this);
        *p_head      = _req;
        this->body() = std::move(_req.body());
    }
    HttpRequest::HttpRequest(boost::beast::http::request<boost::beast::http::string_body> const& _req) {
        auto* p_head = static_cast<HttpRequest::header_type*>(this);
        *p_head      = _req;
        // this->body().assign(_req.body());
        this->body() = std::move(_req.body());
    }

    std::vector<FormItem> const& HttpRequest::forms() {
        // TODO: 在此处插入 return 语句
        if (m_forms.empty()) {
            parser_parts();
        }
        return m_forms;
    }

    ContentType HttpRequest::content_type() const {
        return ContentType(operator[](boost::beast::http::field::content_type));
    }

    HttpRequest::~HttpRequest() {
    }

}  // namespace rdhttp
